<template>
	<div class="v-echarts"></div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator'
import * as echarts from 'echarts'
import { Option } from '../../types/echarts'
import axios from 'axios'

@Component
export default class Echarts extends Vue {
	@Prop({ default: null }) option!: Option
	@Prop({ default: '' }) theme!: string

	// initial data
	private myChart: any = null

	@Watch('option', { immediate: true, deep: true })
	updateChart(newVal: Option | null): void {
		if (!newVal) return
		this.initChart()
	}

	mounted(): void {
		// this.initChart()
	}

	private initChart(): void {
		this.$nextTick(() => {
			this.registerTheme().then(() => {
				this.myChart.setOption(this.option)
				this.myChart.on('click', (params: any): void => {
					this.$emit('click', params)
				})
				window.addEventListener('resize', this.resizeChart)
			})
		})
	}

	private async registerTheme(): Promise<void> {
		const el: any = this.$el
		if (this.myChart) {
			this.myChart.dispose()
		}
		if (this.theme) {
			await axios
			  .get("static/themes/" + this.theme + ".json")
			  .then((res) => {
			    echarts.registerTheme(this.theme, res.data.theme)
			    this.myChart = echarts.init(el, this.theme)
			  })
		} else {
			this.myChart = echarts.init(el)
		}
		this.$emit('init', this.myChart)
	}

	private resizeChart(): void {
		this.myChart.resize()
	}
}
</script>

<style lang="scss" scoped>
.v-echarts {
	width: 100%;
	height: 100%;
}
</style>
